import numpy as np
import numexpr as ne
import pandas as pd
import re, os
from functools import reduce
import colorama
import warnings
warnings.filterwarnings("ignore")
colorama.init(autoreset=True)
TEXT_COLOR_RED = colorama.Fore.RED
TEXT_COLOR_GREEN = colorama.Fore.GREEN
TEXT_COLOR_YELLOW = colorama.Fore.YELLOW
TEXT_COLOR_END = colorama.Fore.RESET

root_path=os.path.join(os.getcwd(),"CE_WAD")
def fout(input_file_name,process_name,out_format):
    info_list=input_file_name.split(".")[0].split("-")[0].split("_")
    fout_prefix = f'{process_name}_'+info_list[-1]
    ntry = 0
    while True:
        if ntry == 0:
            fout = fout_prefix + f'.{out_format}'
        else:
            fout = fout_prefix + '-%d.%s' % (ntry,out_format)
        if os.access(os.path.join(root_path,fout), os.F_OK):
            ntry += 1
        else:
            break
    return fout

def matched_sweep(CE_WAD_Ref,CE_WAD_5):
    info_ref=CE_WAD_Ref.split(".")[0].split("_")
    info_per = CE_WAD_5.split(".")[0].split("_")
    try:
        mat_ref,mat_per=pd.read_csv(os.path.join(root_path,f"MatchedRGB_{info_ref[-1]}.csv")),pd.read_csv(os.path.join(root_path,f"MatchedRGB_{info_per[-1]}.csv"))
    except:
        print("Matched file 读取失败! 可能不存在对应rgb的Matched文件")
    matched_list=list(set(mat_per.columns)&set(mat_ref.columns))
    matched_list.sort(key=mat_ref.columns.to_list().index)
    return matched_list

def main(ce_wad_ref, ce_wad_5):
    cancu_df=ce_wad_ref
    cancu_df["U"]=ce_wad_5["U"]
    cancu_df["V"] = ce_wad_5["V"]
    cancu_df['diff_u'], cancu_df['diff_v'] = ce_wad_5["U"] - cancu_df["U_0"], ce_wad_5["V"] - cancu_df["V_0"]
    return cancu_df
if __name__ == '__main__':
    root_path=os.getcwd()
    ce_wad_inp = input('Please input the file to Caculate dif_U,dif_v,which Corespnding to CE_WAD_Ref.csv CE_WAD_5.csv: \n').strip().split()
    ce_wad_ref, ce_wad_5 = pd.read_csv(os.path.join(root_path, ce_wad_inp [0])), pd.read_csv(os.path.join(root_path, ce_wad_inp [1]))
    cancu_df=main(ce_wad_ref, ce_wad_5 )
    fout=fout(ce_wad_inp[1],"Diff_UV","csv")
    cancu_df.to_csv(os.path.join(root_path,fout), index=False)
    print( 'Write output file '+TEXT_COLOR_GREEN+"%s"% (fout,)+TEXT_COLOR_END+' successfully!' )

# CE_WAD_Ref-1.csv CE_WAD_5-1.csv